
import { useEffect, useState } from 'react';
import { SwipeCell, Flex, Button, Image, Typography, Stepper, Checkbox, SubmitBar, Toast, Dialog, } from 'react-vant';
import '../sass/Shopbag.scss'
import axios from 'axios'
import { useDispatch } from 'react-redux'
import { changeCount } from '../store/store'
import { useNavigate } from 'react-router-dom'
import { NavBar } from 'react-vant';


function Shopbag() {

	let [shopbagData, setShopbagData] = useState([])
	let [allChoose, setAllChoose] = useState(false)
	let [totalPrice, setTotalPrice] = useState(0)
	let bgimg = require('../images/shopbag_bg.png')
	let [editStatus,setEditStatus] = useState(false)

	let dispath = useDispatch()
	let navigate = useNavigate()

	//获取购物袋数据
	let getShopbagData = () => {
		axios({
			method: 'get',
			url: '/findAllShopcart'
		}).then(res => {
			if (res.data.code === 5000) {
				res.data.result.forEach(item => {
					item.isCheck = false;
				})
				setShopbagData(res.data.result);
			}
		})

	}
	//更新数量
	let updateCount = (item, value) => {
		item.count = value
		setShopbagData([...shopbagData])
		axios({
			method: 'post',
			url: '/modifyShopcartCount',
			data: {
				sid: item.sid,
				count: value
			}
		}).then(res => {
			if (res.data.code == 6000) {
				let totalCount = 0
				shopbagData.forEach(item => {
					totalCount += item.count
				})
				dispath(changeCount(totalCount))
			}
		})
		getTotalPrice()
	}
	//全选
	let ChooseAll = status => {
		setAllChoose(status)
		shopbagData.forEach(item => {
			item.isCheck = status
		})
		setShopbagData([...shopbagData])
		getTotalPrice()
	}
	//单选
	let chooseOne = (item, status) => {
		item.isCheck = status
		setShopbagData([...shopbagData])
		getTotalPrice()
		for (let i = 0; i < shopbagData.length; i++) {
			if (!shopbagData[i].isCheck) {
				setAllChoose(false)
				return
			}
		}
		setAllChoose(true)
	}
	//获取总价
	let getTotalPrice = () => {
		let totalMoney = 0
		shopbagData.forEach(item => {
			if (item.isCheck) {
				totalMoney += item.price * item.count * 100
			}
		})
		setTotalPrice(totalMoney)
	}
	//提交订单
	let commit = () => {
		if (!editStatus) {
			let sids = []
			shopbagData.forEach(item => {
				if (item.isCheck) {
					sids.push(item.sid)
				}
			})
			if (sids.length == 0) {
				Toast({
					message: '请选择商品'
				})
			} else {
				navigate(`/pay`, { state: { sids } })
			}
		}else {
			Dialog.confirm({
				title: '提示',
				message: '确定要删除吗?',
			})
			.then(() => {
				let sids = []
				shopbagData.forEach(item => {
					if(item.isCheck) {
						sids.push(item.sid)
					}
				})
				shopbagData = shopbagData.filter(item => !item.isCheck)
				setShopbagData([...shopbagData])
				getTotalPrice()
				let count = 0
				shopbagData.forEach(item => {
					count += item.count
				})
				dispath(changeCount(count))
				axios({
					method:'post',
					url:'/deleteShopcart',
					data:{
						sids:JSON.stringify(sids)
					},
				}).then(res => {
					if(res.data.code==7000&&shopbagData.length==0){
						setAllChoose(false)
					}
				})
			})
		}
		
	}
	//返回上一级
	let goBack = () => {
		navigate(-1)
	}
	//编辑
	let edit = () => {
		editStatus=!editStatus
		setEditStatus(editStatus)
	}
	//删除
	let removeItem = (index) => {
		Dialog.confirm({
			title: '提示',
			message: '确定要删除吗?',
		})
		.then(() => {
			let sids = JSON.stringify([shopbagData[index].sid])
			shopbagData.splice(index, 1)
			setShopbagData([...shopbagData])
			getTotalPrice()
			let count = 0
			shopbagData.forEach(item => {
				count += item.count
			})
			dispath(changeCount(count))
			axios({
				method:'post',
				url:'/deleteShopcart',
				data:{
					sids
				},
			}).then(res => {
				if(res.data.code==7000){
					for (let i = 0; i < shopbagData.length; i++) {
						if (!shopbagData[i].isCheck) {
							setAllChoose(false)
							return
						}
					}
					setAllChoose(true)
				}
			})
		})
		.catch(() => {
		})
	}

	useEffect(() => {
		getShopbagData()
		setAllChoose(false)
	}, [])

	return (
		<div className="shopbag">
			<NavBar
				title="购物袋"
				leftText="返回"
				rightText={!editStatus?'编辑':'完成'}
				onClickLeft={() => { goBack() }}
				onClickRight={() => { edit() }}
			/>
			<div className='top-img'>
				<img className='auto-img' src={bgimg} alt="" />
			</div>
			<div className="shop-list-wrap">
				<div className="shop-list">
					{
						shopbagData.map((item, index) => {
							return (
								<div className='shop-item' key={item.sid}>
									<SwipeCell
										rightAction={
											<Button style={{ height: '100%' }} square type="danger" onClick={() => { removeItem(index) }}>
												删除
											</Button>
										}
									>
										<Flex className="demo-product-card" align="stretch">
											<Checkbox checked={item.isCheck} checkedColor='#ee0a24' onChange={status => chooseOne(item, status)}>
											</Checkbox>
											<Image className="demo-product-card__img" src={item.small_img} />
											<Flex direction="column" justify="between" className="demo-product-card__content">
												<div>
													<div className='shop-msg ellipse-text'>
														<div className="name">{item.name}</div>
														<div className="rule ellipse-text">{item.rule}</div>
													</div>
													<div className='desc'>{item.enname}</div>
												</div>
												<Flex justify="between" align="center">
													<Typography.Text strong size="lg" type='danger'>
														¥{item.price}
													</Typography.Text>
													<Stepper theme='round' value={item.count} buttonSize='22' min='1' defaultValue='1' onChange={value => { updateCount(item, value) }}></Stepper>
												</Flex>
											</Flex>
										</Flex>
									</SwipeCell>
								</div>
							)
						})
					}
				</div>
			</div>
			<SubmitBar
				price={totalPrice}
				buttonText={!editStatus?"提交订单":"删除选择"}
				onSubmit={() => { commit() }}
			>
				<Checkbox checkedColor='red' onChange={status => ChooseAll(status)} checked={allChoose}>全选</Checkbox>
			</SubmitBar>
		</div>
	)
}

export default Shopbag